package CSC;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ChatServer {
    private ServerSocket server;
    public Gson gson = new Gson();
    public  Map<Integer, MessageBean> Messagemap = new HashMap<Integer, MessageBean>();
    public Map<Integer, Socket> SocketMap=new HashMap<Integer, Socket>();
    public  List<Socket> listSocket=new ArrayList<Socket>();
    public void initServer() {
        try {
            server = new ServerSocket(SocketUrls.PORT);
            createMessage();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 创建消息管理，一直接收消息
     */
    private void createMessage() {
        Socket socket = null;
        try {
            System.out.println("等待用户接入 : ");
            // 使用accept()阻塞等待客户请求
            socket = server.accept();
            listSocket.add(socket);
            System.out.println("用户接入 : " + socket.getPort());
            // 开启一个子线程来等待另外的socket加入
            new Thread(new Runnable() {
                public void run() {
                    createMessage();
                }
            }).start();
            // 向客户端发送信息
            // final OutputStream output = socket.getOutputStream();
            // 从客户端获取信息
            BufferedReader bff = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            // 读取发来服务器信息
            String line = null;
            // 循环一直接收当前socket发来的消息
                // System.out.println("内容 : " + bff.readLine());
                // 获取客户端的信息
                //PrintWriter write=new PrintWriter(socket.getOutputStream());
                line = bff.readLine();
                MessageBean messageBean = gson.fromJson(line, MessageBean.class);
                if(messageBean.isFirst()){
                    setUserInforSocket(messageBean,socket);
                    //System.out.println("OK");
                }
                while (!messageBean.getContent().equals(null)&&!messageBean.getContent().equals("")&&!messageBean.getContent().equals("end")){                  
                    if(!messageBean.getContent().equals("&")){
                    System.out.println("用户 : " + messageBean.getUserName());
                    System.out.println("内容 : " + messageBean.getContent());
                    findFriend((int) messageBean.getFriendID(),messageBean);
                    }
                    line = bff.readLine();
                    messageBean = gson.fromJson(line, MessageBean.class);
                }

            // server.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("错误 : " + e.getMessage());

        }
    }
    //将客户端信息存储起来
    private void setUserInforSocket(MessageBean message,Socket socket){
        if (message != null && Messagemap.get(message.getUserID()) == null&& SocketMap.get(message.getUserID()) == null) {

            Messagemap.put((int) message.getUserID(), message);
            SocketMap.put((int) message.getUserID(), socket);

        }
    }
    //通过friendID寻找通信对象，将message对象存储的消息取出，传递出去
    private void findFriend(int id,MessageBean messageBean){    
        if(SocketMap.get(id)!=null && SocketMap!=null){
            Socket socket=SocketMap.get(id);
            MessageBean M=Messagemap.get(id);
            M.setContent(messageBean.getContent());
            try {
                PrintWriter write0=new PrintWriter(socket.getOutputStream());
                String t=gson.toJson(M);
                String s=gson.toJson(messageBean);
                System.out.println(t);
                System.out.println(s);
                write0.println(s);
                write0.flush();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
    public static void main(String[] args) {
        new ChatServer().initServer();
    }
}
